<template>
  <!--  收款账号-->
  <div class="address" :style="{ paddingTop: capsuleTop + 'px' }">
    <Return />

    <!-- 收款账号列表 -->
    <scroll-view
      v-if="!showAddForm"
      class="address-content"
      scroll-y="true"
      :style="{ height: contentHeight + 'px' }"
    >
      <template v-for="(item, index) in collectionList" :key="item.id">
        <div class="address-content-item">
          <div class="address-content-item-header">
            <div class="logo-zi">{{ getFirstChar(item.name) }}</div>
            <div class="header-content">
              <div class="header-content-top">
                <div>{{ item.name }}</div>
                <div>{{ item.account }}</div>
              </div>
              <div>{{ getPaymentTypeName(item.paymentType) }}</div>
            </div>
            <div @click="editCollection(item)" class="edit-btn">修改</div>
          </div>
          <div class="page-line"> </div>
          <div class="address-content-item-footer">
            <wd-checkbox v-model="item.isDefault" @change="(e) => handleDefaultChange(e, item)">
              <div>默认收款账号</div>
            </wd-checkbox>
            <div class="right">
              <div @click="deleteCollection(item)" class="delete-btn">删除</div>
            </div>
          </div>
        </div>
      </template>
    </scroll-view>

    <!-- 添加/编辑收款账号表单 -->
    <div class="add-address" v-if="showAddForm">
      <div class="add-address-title">
        <div class="add-address-title-text">
          <span class="iconfont icon-edit"></span>
          {{ isEditing ? '编辑收款信息' : '添加收款信息' }}
        </div>
        <wd-checkbox v-model="formData.isDefault" @change="handleFormDefaultChange">
          <div class="title-checkbox">默认收款账号</div>
        </wd-checkbox>
      </div>
      <div class="add-address-content">
        <div class="add-address-content-item">
          <label class="feedback-label" for="name">姓名</label>
          <input
            id="name"
            class="feedback-input"
            type="text"
            placeholder="请输入联系人姓名"
            v-model="formData.name"
            maxlength="20"
          >
        </div>
        <div class="add-address-content-item">
          <label class="feedback-label" for="account">账号</label>
          <input
            id="account"
            class="feedback-input"
            type="text"
            placeholder="请输入收款账号"
            v-model="formData.account"
            maxlength="50"
          >
        </div>
        <div class="add-address-content-item">
          <label class="feedback-label">收款类型</label>
          <picker
            class="feedback-input picker-input"
            :value="formData.paymentType"
            :range="paymentTypeOptions"
            range-key="label"
            @change="handlePaymentTypeChange"
          >
            <view class="picker-text" style="width: 400rpx;">
              {{ getPaymentTypeName(formData.paymentType) || '请选择收款类型' }}
            </view>
          </picker>
        </div>
        <div class="add-address-content-item" v-if="formData.paymentType === 2">
          <label class="feedback-label" for="bankName">开户行</label>
          <input
            id="bankName"
            class="feedback-input"
            type="text"
            placeholder="请输入开户行名称"
            v-model="formData.bankName"
            maxlength="50"
          >
        </div>
      </div>
      <div class="footer add-footer">
        <button class="footer-btn main-btn" @click="saveCollection">
          {{ isEditing ? '保存修改' : '添加收款账号' }}
        </button>
        <button class="footer-title cancel-btn" @click="cancelAdd">取消</button>
      </div>
    </div>

    <!-- 底部操作按钮（只在列表页显示） -->
    <div class="footer" v-if="!showAddForm">
      <div class="footer-title" @click="showManageModal">管理</div>
      <div class="footer-btn" @click="showAdd">添加收款账号</div>
    </div>

    <!-- 管理弹窗 -->
    <wd-popup v-model="showManage" position="bottom" :style="{ height: '300rpx' }">
      <div class="manage-popup">
        <div class="manage-title">管理收款账号</div>
        <div class="manage-options">
          <div class="manage-option" @click="batchDelete">
            <div class="option-icon">🗑️</div>
            <div class="option-text">批量删除</div>
          </div>
        </div>
        <div class="manage-cancel" @click="showManage = false">取消</div>
      </div>
    </wd-popup>

    <!-- 确认删除弹窗 -->
    <wd-popup v-model="showDeleteConfirm" position="center" :style="{ width: '600rpx' }">
      <div class="delete-confirm">
        <div class="delete-title">确认删除</div>
        <div class="delete-content">确定要删除这个收款账号吗？删除后无法恢复。</div>
        <div class="delete-actions">
          <div class="delete-cancel" @click="showDeleteConfirm = false">取消</div>
          <div class="delete-confirm-btn" @click="confirmDelete">确认删除</div>
        </div>
      </div>
    </wd-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { Fetch } from '@/composables/useFetch'
import Return from '@/components/Return.vue'

// 响应式数据
const capsuleTop = ref(0)
const contentHeight = ref(0)
const collectionList = ref([])
const showAddForm = ref(false)
const isEditing = ref(false)
const showManage = ref(false)
const showDeleteConfirm = ref(false)
const currentDeleteItem = ref(null)
const loading = ref(false)

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  account: '',
  paymentType: 0,
  bankName: '',
  isDefault: false
})

// 支付类型选项
const paymentTypeOptions = ref([
  { label: '支付宝', value: 0 },
  { label: '微信', value: 1 },
  { label: '银行卡', value: 2 },
])

// 计算属性
const getFirstChar = (name) => {
  return name ? name.charAt(0) : '收'
}

const getPaymentTypeName = (type) => {

  const option = paymentTypeOptions.value.find(item => item.value == type)

  return option ? option.label : '未知类型'
}

// 生命周期
onMounted(() => {
  const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  capsuleTop.value = menuButtonInfo.bottom + 20
  contentHeight.value = wx.getSystemInfoSync().windowHeight - menuButtonInfo.bottom - 113
  loadCollectionList()
})

// 方法
const loadCollectionList = async () => {
  try {
    loading.value = true
    const { status, data } = await Fetch('collection/list', { method: 'get' })
    if (status === 200 && data.code === 0) {
      collectionList.value = data.result || []
    } else {
      // 模拟数据，实际项目中删除这部分
      collectionList.value = [
        {
          id: 1,
          name: '张三',
          account: '13800138000',
          paymentType: 0,
          bankName: '',
          isDefault: true
        },
        {
          id: 2,
          name: '李四',
          account: '6222021234567890123',
          paymentType: 2,
          bankName: '中国工商银行',
          isDefault: false
        }
      ]
    }
  } catch (error) {
    console.error('加载收款账号列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  formData.id = null
  formData.name = ''
  formData.account = ''
  formData.paymentType = 0
  formData.bankName = ''
  formData.isDefault = false
  isEditing.value = false
}

const validateForm = () => {
  if (!formData.name.trim()) {
    uni.showToast({
      title: '请输入联系人姓名',
      icon: 'none'
    })
    return false
  }
  if (!formData.account.trim()) {
    uni.showToast({
      title: '请输入收款账号',
      icon: 'none'
    })
    return false
  }
  if (formData.paymentType === 2 && !formData.bankName.trim()) {
    uni.showToast({
      title: '请输入开户行名称',
      icon: 'none'
    })
    return false
  }
  return true
}

const saveCollection = async () => {
  if (!validateForm()) return

  try {
    loading.value = true
    const url = isEditing.value ? 'collection/update' : 'collection/add'
    const method = isEditing.value ? 'put' : 'post'

    const { status, data } = await Fetch(url, {
      method,
      data: formData
    })

    if (status === 200 && data.code === 0) {
      uni.showToast({
        title: isEditing.value ? '修改成功' : '添加成功',
        icon: 'success'
      })
      resetForm()
      loadCollectionList()
    } else {
      uni.showToast({
        title: data.msg || '操作失败',
        icon: 'error'
      })
    }
  } catch (error) {
    console.error('保存收款账号失败:', error)
    uni.showToast({
      title: '操作失败',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

const editCollection = (item) => {
  isEditing.value = true
  Object.assign(formData, { ...item })
  showAddForm.value = true
}

const deleteCollection = (item) => {
  currentDeleteItem.value = item
  showDeleteConfirm.value = true
}

const confirmDelete = async () => {
  if (!currentDeleteItem.value) return

  try {
    loading.value = true
    const { status, data } = await Fetch('collection/delete', {
      method: 'delete',
      data: { id: currentDeleteItem.value.id }
    })

    if (status === 200 && data.code === 0) {
      uni.showToast({
        title: '删除成功',
        icon: 'success'
      })
      loadCollectionList()
    } else {
      uni.showToast({
        title: data.msg || '删除失败',
        icon: 'error'
      })
    }
  } catch (error) {
    console.error('删除收款账号失败:', error)
    uni.showToast({
      title: '删除失败',
      icon: 'error'
    })
  } finally {
    loading.value = false
    showDeleteConfirm.value = false
    currentDeleteItem.value = null
  }
}

const handleDefaultChange = async (e, item) => {
  try {
    const { status, data } = await Fetch('collection/setDefault', {
      method: 'post',
      data: { id: item.id, isDefault: e }
    })

    if (status === 200 && data.code === 0) {
      // 更新本地数据
      collectionList.value.forEach(collection => {
        collection.isDefault = collection.id === item.id ? e : false
      })
      uni.showToast({
        title: e ? '已设为默认' : '已取消默认',
        icon: 'success'
      })
    } else {
      // 恢复原状态
      item.isDefault = !e
      uni.showToast({
        title: data.msg || '操作失败',
        icon: 'error'
      })
    }
  } catch (error) {
    console.error('设置默认账号失败:', error)
    item.isDefault = !e
    uni.showToast({
      title: '操作失败',
      icon: 'error'
    })
  }
}

const handleFormDefaultChange = (e) => {
  formData.isDefault = e
}

const handlePaymentTypeChange = (e) => {
  formData.paymentType = e.detail.value
  if (e.detail.value !== 2) {
    formData.bankName = ''
  }
}

const showManageModal = () => {
  showManage.value = true
}

const batchDelete = () => {
  showManage.value = false
  uni.showModal({
    title: '批量删除',
    content: '确定要删除所有收款账号吗？',
    success: (res) => {
      if (res.confirm) {
        // 实现批量删除逻辑
        console.log('批量删除')
      }
    }
  })
}

const exportData = () => {
  showManage.value = false
  // 实现导出逻辑
  console.log('导出数据')
  uni.showToast({
    title: '导出功能开发中',
    icon: 'none'
  })
}

// 新增/编辑切换
const showAdd = () => {
  resetForm()
  showAddForm.value = true
  isEditing.value = false
}
const cancelAdd = () => {
  showAddForm.value = false
  resetForm()
}
</script>

<style lang="scss">
page {
  background: #F5F5F5;
}

.address {
  .address-content {
    padding-bottom: 20rpx;

    .address-content-item {
      width: 672rpx;
      background: #FFFFFF;
      border-radius: 20rpx 20rpx 20rpx 20rpx;
      padding: 46rpx 24rpx 26rpx;
      box-sizing: border-box;
      margin: 0 auto 20rpx;

      .address-content-item-header {
        display: flex;
        align-items: center;

        .logo-zi {
          width: 70rpx;
          height: 70rpx;
          background: #FDF8F1;
          font-weight: bold;
          font-size: 30rpx;
          color: #E68932;
          line-height: 70rpx;
          text-align: center;
          font-style: normal;
          text-transform: none;
          margin-right: 20rpx;
          border-radius: 50%;
        }

        .header-content {
          margin-right: auto;
          color: #999999;
          font-size: 24rpx;

          .header-content-top {
            display: flex;
            align-items: center;
            color: #111111;
            margin-bottom: 10rpx;

            view {
              &:nth-child(1) {
                font-size: 28rpx;
                font-weight: bold;
                margin-right: 10rpx;
              }

              &:nth-child(2) {
                font-size: 24rpx;
              }
            }
          }
        }

        .edit-btn {
          font-size: 24rpx;
          color: #007AFF;
          padding: 10rpx;
        }
      }

      .page-line {
        width: 100%;
        height: 2rpx;
        background: #F1F1F2;
        margin: 44rpx 0;
      }

      .address-content-item-footer {
        display: flex;
        align-items: center;

        .right {
          margin-left: auto;
          font-size: 24rpx;
          color: #999999;
          line-height: 34rpx;
          text-align: left;
          font-style: normal;
          text-transform: none;

          .delete-btn {
            color: #FF3B30;
            padding: 10rpx;
          }
        }
      }
    }
  }


  .add-address {
    width: 670rpx;
    background: #fff;
    border-radius: 24rpx;
    margin: 0 auto;
    padding: 40rpx 32rpx 24rpx 32rpx;
    box-sizing: border-box;
    box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.06);

    .add-address-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-weight: bold;
      font-size: 36rpx;
      color: #222;
      margin-bottom: 48rpx;

      .add-address-title-text {
        display: flex;
        align-items: center;
        font-size: 36rpx;
        color: #222;
        .iconfont {
          font-size: 32rpx;
          color: #fbe050;
          margin-right: 12rpx;
        }
      }

      .title-checkbox {
        font-weight: 400;
        font-size: 26rpx;
        color: #999;
        margin-left: 12rpx;
      }
    }

    .add-address-content {
      .add-address-content-item {
        display: flex;
        align-items: center;
        margin-bottom: 36rpx;

        .feedback-label {
          font-size: 28rpx;
          color: #333;
          width: 120rpx;
          text-align: left;
          font-weight: 500;
          margin-right: 16rpx;
        }

        .feedback-input {
          flex: 1;
          height: 80rpx;
          padding: 0 28rpx;
          border: 1rpx solid #e5e5e5;
          border-radius: 16rpx;
          background: #f8f8f8;
          font-size: 26rpx;
          color: #222;
          transition: border 0.2s;
          outline: none;
          box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);

          &:focus {
            border: 1rpx solid #fbe050;
            background: #fffbe6;
          }

          // 添加picker相关样式
          &.picker-input {
            display: flex;
            align-items: center;
            padding: 0;

            .picker-text {
              flex: 1;
              height: 80rpx;
              padding: 0 28rpx;
              display: flex;
              align-items: center;
              font-size: 26rpx;
              color: #222;

              &:empty::before {
                content: '请选择收款类型';
                color: #999;
              }
            }
          }
        }
      }
    }

    .add-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 32rpx;

      .main-btn {
        width: 60%;
        height: 88rpx;
        background: linear-gradient(90deg, #ffe259 0%, #ffa751 100%);
        color: #222;
        font-size: 30rpx;
        font-weight: bold;
        border: none;
        border-radius: 44rpx;
        box-shadow: 0 4rpx 16rpx rgba(255, 224, 80, 0.15);
        transition: background 0.2s;
        &:active {
          background: #ffd700;
        }
      }
      .cancel-btn {
        width: 36%;
        height: 88rpx;
        background: #f5f5f5;
        color: #888;
        font-size: 30rpx;
        border: none;
        border-radius: 44rpx;
        margin-left: 24rpx;
        font-weight: 500;
        transition: background 0.2s;
        &:active {
          background: #e0e0e0;
        }
      }
    }
  }

  .footer {
    height: 136rpx;
    background: #FFFFFF;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    font-weight: bold;
    font-size: 28rpx;
    color: #333333;
    text-align: center;
    font-style: normal;
    text-transform: none;
    line-height: 84rpx;
    padding: 20rpx 40rpx 0;
    box-sizing: border-box;
    z-index: 10;

    .footer-title {
      width: 184rpx;
      height: 84rpx;
      background: #F7F7F7;
      border-radius: 50rpx 50rpx 50rpx 50rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .footer-btn {
      width: 462rpx;
      height: 84rpx;
      background: #FBE050;
      border-radius: 42rpx 42rpx 42rpx 42rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 100rpx 0 40rpx 0;
    .empty-icon {
      font-size: 80rpx;
      margin-bottom: 20rpx;
    }
    .empty-text {
      font-size: 32rpx;
      color: #999;
      margin-bottom: 10rpx;
    }
    .empty-desc {
      font-size: 24rpx;
      color: #bbb;
    }
  }
}

/* 管理弹窗样式 */
.manage-popup {
  padding: 40rpx 30rpx;
  .manage-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
  }
  .manage-options {
    display: flex;
    justify-content: space-around;
    margin-bottom: 30rpx;
    .manage-option {
      display: flex;
      flex-direction: column;
      align-items: center;
      .option-icon {
        font-size: 40rpx;
        margin-bottom: 10rpx;
      }
      .option-text {
        font-size: 28rpx;
      }
    }
  }
  .manage-cancel {
    text-align: center;
    color: #007AFF;
    font-size: 28rpx;
    margin-top: 20rpx;
  }
}

/* 删除确认弹窗样式 */
.delete-confirm {
  padding: 40rpx 30rpx;
  .delete-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    text-align: center;
  }
  .delete-content {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 30rpx;
    text-align: center;
  }
  .delete-actions {
    display: flex;
    justify-content: space-between;
    .delete-cancel, .delete-confirm-btn {
      width: 45%;
      height: 70rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 35rpx;
      font-size: 28rpx;
    }
    .delete-cancel {
      background: #f5f5f5;
      color: #333;
    }
    .delete-confirm-btn {
      background: #FF3B30;
      color: #fff;
    }
  }
}

::v-deep {
  .wd-upload {
    margin-top: 30rpx;
  }
  .wd-input {
    &::after {
      display: none !important;
    }
    .wd-input__inner {
      text-align: right;
      font-size: 28rpx;
      color: #999999;
    }
  }
}
</style>
